package com.qar.exp;



import com.qar.resp.ResultData;
import com.qar.resp.ReturnCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @auther zzyy
 * @create 2023-12-22 17:09
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler
{

    /**
     * 处理业务异常
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public ResultData<String> handleBusinessException(BusinessException e, HttpServletRequest request)
    {
        System.out.println("#####come in GlobalExceptionHandler的handleBusinessException方法，主管自定义的BusinessException");
        log.error("请求：{}，发生异常：{}", request.getRequestURL(), e.getMessage(), e);
        return ResultData.fail(e.getCode(), e.getMessage()+"  你的请求url："+request.getRequestURL());
    }


    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultData<String> exception(Exception e)
    {
        System.out.println("#####come in GlobalExceptionHandler的exception方法，主管RuntimeException");
        log.error("全局异常信息:{}",e.getMessage(),e);

        return ResultData.fail(ReturnCodeEnum.RC500.getCode(), e.getMessage());
    }

    /**
     * 处理SpringBoot参数校验异常
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(BindException.class)
    public ResultData<String> handleBindException(BindException e, HttpServletRequest request) {
        log.info("请求：{}，发生异常：{}", request.getRequestURL(), e.getMessage(), e);
        String message = e.getAllErrors().get(0).getDefaultMessage();
        return ResultData.fail(ReturnCodeEnum.REQPARAM_ISEXCEPTION.getCode(), e.getMessage());
    }

    /**
     * 处理其他异常,会返回code为500的一个异常
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(Exception.class)
    public ResultData<String> handleException(Exception e, HttpServletRequest request) {
        log.info("请求：{}，发生异常：{}", request.getRequestURL(), e.getMessage(), e);
        //会返回code为500的一个异常
        return ResultData.fail(ReturnCodeEnum.RC500.getCode(), e.getMessage());
    }
}
